package code.generator.main;


import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ConvertorUtil {

    private static final Pattern camelPattern = Pattern.compile("[A-Z]]");
    private static final Pattern linePattern = Pattern.compile("_(\\w)");

    public static void main(String[] args) {
        System.out.println(toCamelCaseClassName("USER_INFO".toLowerCase()));
    }


    /**
     * user_id  ->  userId
     * @param s
     * @return
     */
    public static String toCamelCaseClassName(String s){
        s = s.toLowerCase();
        Matcher matcher = linePattern.matcher(s);
        StringBuffer sb = new StringBuffer();
        while( matcher.find() ){
            matcher.appendReplacement(sb,matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        s = sb.toString();
        String firstChar = String.valueOf(s.charAt(0)).toUpperCase();

        return firstChar+s.substring(1);
    }

    /**
     * user_id  ->  userId
     * @param s
     * @return
     */
    public static String toCamelCase(String s){
        Matcher matcher = linePattern.matcher(s);
        StringBuffer sb = new StringBuffer();
        while( matcher.find() ){
            matcher.appendReplacement(sb,matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * userId  ->   user_id
     * @param s
     * @return
     */
    public static String toLineCase(String s){
        Matcher matcher = camelPattern.matcher(s);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()){
            matcher.appendReplacement(sb,"_"+matcher.group(0).toLowerCase());
        }
        return sb.toString();
    }


    /**
     * 数据表字段名转换为驼峰式名字的实体类属性名
     * @param tabAttr   数据表字段名
     * @return  转换后的驼峰式命名
     */
    public static String camelize(String tabAttr){
        if(isBlank(tabAttr))
            return tabAttr;
        Pattern pattern = Pattern.compile("(.*)_(\\w)(.*)");
        Matcher matcher = pattern.matcher(tabAttr);

        if(matcher.find()){
            return camelize(matcher.group(1) + matcher.group(2).toUpperCase() + matcher.group(3));
        }else{
            return tabAttr;
        }
    }

    /**
     * 驼峰式的实体类属性名转换为数据表字段名
     * @param camelCaseStr  驼峰式的实体类属性名
     * @return  转换后的以"_"分隔的数据表字段名
     */
    public static String decamelize(String camelCaseStr){
        return isBlank(camelCaseStr) ? camelCaseStr : camelCaseStr.replaceAll("[A-Z]", "_$0").toLowerCase();
    }

    /**
     * 字符串是否为空
     * @param cs   待检查的字符串
     * @return  空：true; 非空：false
     */
    public static boolean isBlank(final CharSequence cs) {
        int strLen;
        if (cs == null || (strLen = cs.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if (!Character.isWhitespace(cs.charAt(i))) {
                return false;
            }
        }
        return true;
    }
}
